<template>
  <div class="app-container">
    <!-- Header头部区域 -->
   <Header />
   <!-- 循环渲染每一个goods的信息 -->
   <Goods v-for="item in list" 
   :key="item.id" 
   :title="item.goods_name" 
   :pic = "item.goods_img" 
   :price="item.goods_price" 
   :state="item.goods_state"
   :id = "item.id"
   @stateChange = "getNewState"
   ></Goods>
   
   <!-- 底部 -->
   <Footer 
    :isFullState="fullState"
    :totalPrice="amt"
    @fullChange = "getFullChange" 
    ></Footer>
  </div>
</template>

<script>
// 导入axios
import axios from 'axios'

// 导入Header组件
import Header from '@/components/Header/Header.vue'
import Goods from '@/components/Goods/Goods.vue'
import Footer from '@/components/Footer/Footer.vue'

export default {
  data(){
    return{
      // 用来存储购物车的列表数据
      list:[],
    }
  },
  methods:{
    //封装请求列表数据的方法
    async initCartList(){
      //调用axios的get方法
      const {data:res} = await axios.get('https://www.escook.cn/api/cart')
      console.log(res);
      if(res.status == 200){
        this.list = res.list
      }
    },
    // 接收子组件传递的数据
    getNewState(e){
      this.list.some(item=>{
        if(item.id == e.id){
          item.goods_state = e.val
        }
      })
    },
    // 获取全选的状态
    getFullChange(val){
      this.list.forEach(item=>item.goods_state = val)
    }
  },
  components:{
    Header,
    Goods,
    Footer
  },
  created(){
    this.initCartList()
  },
  computed:{
    fullState(){
      return this.list.every(item=>item.goods_state)
    },
    // 已勾选商品的总结过
    amt(){
     return this.list.filter(item=>item.goods_state).reduce((total,item)=>total+=item.goods_price*item.goods_count,0)
    }
  }
}
</script>

<style lang = "less" scoped>
/* .app-container {
    padding-top: 45px;
    padding-bottom: 50px;
} */
</style>